import { call, put, 
    takeEvery,
    takeLatest,
 } from 'redux-saga/effects'

import * as Constants from '../../constants'

const api = {
    login() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (Math.random() > 0.5) {
                    resolve({
                        id: 1,
                        name: 'xinglong.shi'
                    })
                } else {
                    reject('登录失败')
                }
            }, 1e3)
        })
    }
}

// work saga
function* login () {
    console.log(1);
    yield put({ type: Constants.LOGIN_REQUEST })
    try {
        let res = yield call(api.login, { username: 'abc', pwd: 123 })
        console.log(2);
        yield put({ type: Constants.LOGIN_SUCCESS, payload: res })
    } catch (error) {
        console.log(3);
        yield put({ type: Constants.LOGIN_ERROR, payload: error })
    }
}

export default function* () {
    console.log('my saga')
    yield takeEvery(Constants.LOGIN, login)
}
